/*
	本程序实现的功能是对于客户端的socket套接字进行接受
	作者：杨磊
*/
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include <fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>

#define SIZE 1000     
#define PORT 9999
#define IP "192.168.0.115"
int service_program();

int service_program()
{
	int socketID = 0;
	int addrLength = 0;
	int ret = 0;
	int on = 1;
	struct sockaddr_in addr;
	char buf[SIZE] = {0};
	//创建套接字 
	socketID = socket(AF_INET,SOCK_STREAM,0);
	if(0 > socketID)
	{
		perror("creat socket error ");
		return -1;
	}
	printf("socket ok %d\r\n",socketID);
	
	
	//绑定地址
	addrLength = sizeof(addr);
	memset(&addr,0,addrLength);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = INADDR_ANY;
	ret = bind(socketID,(struct sockaddr*)&addr,addrLength);
	if(ret < 0)
	{
		perror("bind error");
		close(socketID);
		return -1;
	}
	printf("bind ok\r\n");
	
	//监听
	
	listen(socketID,5);
	
	//接受连接
	int newID = accept(socketID,(struct sockaddr*)&addr,&addrLength);
	if(0 > newID)
	{
		perror("accept error!");
		close(socketID);
		return -1;
	}
	printf("client connect success,port=%d\n\r",ntohs(addr.sin_port));
	
	//通信
	
	ret  = read(newID,buf,SIZE - 1);
	if(ret > 0)
	{
		printf("server get:%s,%d\r\n",buf,ret);
	}	
	if(ret < 0)
	{
		printf("server get error!");
	}
	int fd = open("getdata.txt",O_WRONLY|O_TRUNC|O_CREAT,0666);
	if(fd < 0)
	{
		perror("open error!");
		
		return -1;
	}
	write(fd,buf,SIZE - 1);
	printf("write success!");
	/*memset(buf,0,SIZE);
	
	fgets(buf,SIZE - 1,stdin);
	ret = send(newID,buf,strlen(buf),0);
	if(ret > 0)
	{
		printf("server send ok\r\n");
	}*/
	//关闭套接字  close()
	close(newID);
	close(socketID);
	return 0;
}
int main()
{
	service_program();
	return 0;
	
}
